package com.api.shopapi;

import org.apache.catalina.connector.Connector;
import org.apache.commons.io.FileUtils;
import org.apache.coyote.http11.Http11NioProtocol;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@SpringBootApplication(scanBasePackages = {"com.api.shopapi"})
@EnableScheduling
@MapperScan(basePackages = {"com.api.oa.mapper","com.api.shopapi.mapper"})
@ComponentScan(basePackages = {"com.api.oa","com.api.shopapi"})
@MapperScan("com.api.oa.mapper")
public class ShopapiApplication {

    @Value("${https.port}")
    private Integer port;

    @Value("${https.ssl.key-store}")
    private String key_store;

    @Value("${https.ssl.key-store-password}")
    private String key_store_password;


    public static void main(String[] args) {
        SpringApplication.run(ShopapiApplication.class, args);
    }



    //create single instance
    @Bean
    //@LoadBalanced (负载均衡)
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    //全局配置，启动类，运行跨域
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); // 允许cookies跨域

        //config.addAllowedOrigin("*");// 允许向该服务器提交请求的URI，*表示全部允许。spirngboot2.3.3低版本使用
        config.addAllowedOriginPattern("*");//springboot2.4.0以上高版本使用

        config.addAllowedHeader("*");// 允许访问的头信息,*表示全部
        config.setMaxAge(18000L);// 预检请求的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再预检了
        config.addAllowedMethod("*");// 允许提交请求的方法，*表示全部允许，也可以单独设置GET、PUT等
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }


    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addAdditionalTomcatConnectors(createSslConnector()); // 添加https
        return tomcat;
    }

    // 配置https
    private Connector createSslConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
        try {

            ClassPathResource classPathResource = new ClassPathResource(key_store);
            InputStream inputStream = classPathResource.getInputStream();
            File somethingFile = File.createTempFile("test", ".pfx");
            FileUtils.copyInputStreamToFile(inputStream, somethingFile);


            connector.setScheme("https");
            connector.setSecure(true);
            connector.setPort(port);
            protocol.setSSLEnabled(true);
            protocol.setKeystoreFile(somethingFile.getAbsolutePath());
            protocol.setKeystorePass(key_store_password);
            return connector;

        } catch (IOException ex) {
            ex.printStackTrace();
            throw new IllegalStateException("can't access keystore: [" + "keystore"
                    + "] or truststore: [" + "keystore" + "]", ex);
        }
    }


}
